package datacontrol;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * TODO Description
 * 
 * @author Jeroen
 */
public class DAO {
    private static String dbPath = "";
    
    /**
     * Functie die de connectie ophaalt voor de database.
     * 
     * @return een Connection object. 
     * @throws SQLException 
     */
    public static Connection connect() throws SQLException {
        Connection connection = null;
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DAO.class.getName()).log(Level.WARNING, "JDBC not found...", ex);
        }
        
        connection = DriverManager.getConnection("jdbc:sqlite:"+dbPath);
        return connection;
    }

    /**
     * Creates an HashMap of the ResultSet from the given query.
     * 
     * @param A correct SQL-query
     * @return HashMap<String, String> of the returned ResultSet
     * @throws SQLException, if anything goes wrong (no connection, faulty query)
     */
    public static ArrayList<HashMap<String, String>> selectQuery(String query) throws SQLException {
        Connection con = connect();
        Statement stat = con.createStatement();
        ResultSet res = stat.executeQuery(query);
        ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
        ResultSetMetaData metaData = res.getMetaData();
        int columnCount = metaData.getColumnCount();
        
        int rowsCount = 0;
        while (res.next()) {
            HashMap<String, String> columns = new HashMap<String, String>();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                columns.put(columnName, res.getString(columnName));
            }
            result.add(columns);
            rowsCount++;
        }
        // Close both the ResultSet and the Statement or else the whole
        // database is locked...
        res.close();
        stat.close();
        con.close();
        
        return result;
    }

    public static int executeUpdate(String query) throws SQLException {
        Connection con = connect();
        Statement stat = con.createStatement();
        int rowCount = stat.executeUpdate(query);
        return rowCount;
    }
    
    public static void setDbPath(String path) {
        dbPath = path;
    }
    
    public static String getDBPath() {
        return dbPath;
    }
}